import {unref, computed} from 'vue';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import type {LangType} from '#/lang.d';
import {i18n} from '@/locales/index';
import {setHtmlPageLang, loadLocalePool} from '@/locales/helper';
import {useLocaleStore} from '@/models/modules/locale';

interface LangModule {
  message: any;
  dateLocale: any;
  dateLocaleName: string;
}

function setI18nLanguage(locale: LangType) {
  dayjs.locale('zh-cn');
  const LocaleModel = useLocaleStore();

  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale;
  } else {
    (i18n.global.locale as any).value = locale;
  }
  LocaleModel.setLocaleInfo({locale});
  setHtmlPageLang(locale);
}

export function useLang() {
  const LocaleModel = useLocaleStore();
  const getLocale = computed(() => LocaleModel.getLocale);
  // antd

  const getAntdLocale = computed((): any => {
    // console.log('getLocale', getLocale);
    // console.log(
    //   '999i18n.global.getLocaleMessage<{antdLocale: string}>(unref(getLocale))',
    //   i18n?.global?.getLocaleMessage(unref(getLocale)).antdLocale,
    // );

    if (i18n && i18n.global && i18n.global.getLocaleMessage) {
      const _getLocale = unref(getLocale);
      const getLocaleMessage: any = i18n.global.getLocaleMessage;
      return getLocaleMessage(_getLocale).antdLocale;
    }
    return {};
  });

  // 切换语言
  async function changeLocale(locale: LangType) {
    const globalI18n = i18n.global;
    const currentLocale = unref(globalI18n.locale);
    if (currentLocale === locale) {
      return locale;
    }

    if (loadLocalePool.includes(locale)) {
      setI18nLanguage(locale);
      return locale;
    }
    // const langModule = ((await import(`../lang/${locale}.ts`)) as any).default as LangModule;
    // console.log("lang",locale)
    const langModule = ((await import(`../lang/${locale}.ts`)) as any).default as LangModule;
    if (!langModule) return;

    const {message} = langModule;

    globalI18n.setLocaleMessage(locale, message);
    loadLocalePool.push(locale);

    setI18nLanguage(locale);
    return locale;
  }

  return {
    getLocale,
    changeLocale,
    getAntdLocale,
  };
}
